import axios from 'axios';
import Vue from 'vue';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import router from '../router';
import store from '@/store';
import { getToken } from '../utils';
import { createSign } from './sign';
// 全局成功状态码
const successCode = [0];
// Toast
const Toast = function (info) {
  Vue.prototype.$toast({
    forbidClick: true,
    message: info,
    duration: 1000
  });
};

const API = axios.create({
  baseURL: process.env.VUE_APP_BASEAPI,
  timeout: 15000
});
const errorHandle = async (code, msg) => {
  // 状态码判断
  switch (code) {
    // 99 登录过期
    case 99:
      store.dispatch('resetSessionToken');
      Toast('登录过期,请重新登录');
      setTimeout(() => {
        toLogin();
      }, 1000);
      break;
    case 404:
      Toast('接口暂无资源!');
      break;
    case 500:
      Toast('服务器异常,稍后重试!');
      break;
    default:
      Toast(msg || `接口异常${code}`);
      break;
  }
};
/**
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  router.replace({
    path: '/store/login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  });
};

// 添加请求拦截器
API.interceptors.request.use(config => {
  NProgress.start();
  const token = getToken() || undefined;
  token && (config.headers.session_id = token);
  const Data = {
    ...config.data,
    // timestamp: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    timestamp: new Date().getTime()
  };
  const formatParams = {};
  //  过滤无效参数
  for (const key in Data) {
    if (Data[key] !== undefined && Data[key] !== null && Data[key] !== '') {
      formatParams[key] = Data[key];
    }
  }
  console.log(`请求url: ${config.url} ,参与签名字段:${JSON.stringify(formatParams)}`);
  // 签名
  formatParams.sign = createSign(formatParams);
  config.data = formatParams;
  return config;
}, error => {
  return Promise.error(error);
});

// 响应拦截器
API.interceptors.response.use(response => {
  NProgress.done();
  const { data, config } = response;
  const { code, msg } = data;
  if (successCode.includes(code)) {
    return data;
  } else {
    if ((config.url === 'dy/organ/hook' && code === 1) || (config.url === 'wxv/oauth' && code === 1) || (config.url === 'pms/activity/create' && code === 1)) {
      return data;
    } else {
      errorHandle(code, msg);
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('请求异常:' + JSON.stringify({
        url: config.url,
        code,
        msg
      }) || 'Error');
    }
  }
}, error => {
  NProgress.done();
  const { response, message } = error;
  if (error.response && error.response.data) {
    const { status, data } = response;
    errorHandle(status, data.message || message);
    return Promise.reject(error);
  } else {
    let { message } = error;
    if (message === 'Network Error') {
      message = '接口连接异常';
    }
    if (message.includes('timeout')) {
      message = '接口请求超时';
    }
    if (message.includes('Request failed with status code')) {
      const code = message.substr(message.length - 3);
      message = '接口' + code + '异常';
    }
    Toast(message || '未知异常');
    return Promise.reject(error);
  }
});

export default API;
